package com.littleken.foodieCommon.Utils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.littleken.foodieCommon.Response.ErrorCode;
import com.littleken.foodieCommon.exception.GoffException;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 校验类，完成前端传送过来的参数校验
 * Create by littleken on 2019/1/14 11:01
 */
public class BeanValidator {

    //validator校验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    //校验
    public static <T> Map<String, String> validate(T t, Class... groups) {
        //获得校验类
        Validator validator = validatorFactory.getValidator();
        //校验
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                //当有校验错误时，把错误信息放进errors
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    //多object校验
    public static Map<String, String> validateList(Collection<?> collection) {
        //判空，若空抛出NullPointerException()
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }

    //根据传入object多少实现不同校验
    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));//把所有传入object弄成List
        } else {
            return validate(first, new Class[0]);
        }
    }

    /**
     * 校验方法
     *
     * @param param 参数校验规则
     * @throws RuntimeException
     */
    public static void check(Object param) throws GoffException {
        Map<String, String> map = BeanValidator.validateObject(param);
        //若校验存在问题，抛出ParamException
        if (MapUtils.isNotEmpty(map)) {
            //if (map !=null && map.entrySet().size() >0) {
            throw new GoffException(ErrorCode.PARAMS_INVALID, map.toString());
        }
    }
}

